package com.tanker.common.utils; 

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.apache.commons.codec.binary.Base64;



/** 
 * @comments
 * @author zg 
 * @version 2013年9月25日 
 */
public class CommonUtils {
	private static Logger logger = LoggerFactory.getLogger(CommonUtils.class);
	
	private static final char[] charAndNumArr = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
	private static final char[] UpCharAndNumArr = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9'};
	//生成邀请码，不包括0,1,9,i,l,o,g
	private static final char[] UpCharAndNumArr4INVITECODE = {'a','b','c','d','e','f','h','j','k','m','n','p','q','r','s','t','u','v','w','x','y','z','2','3','4','5','6','7','8'};
	//private static final char[] charArr = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
	private static final char[] numArr = {'0','1','2','3','4','5','6','7','8','9'};
	private static final char[] numArrNoZero = {'1','2','3','4','5','6','7','8','9'};
	private static final Random random = new Random(); 
	private static final int IS_PLATFORM_SHOW = 1;//是否在平台显示  1：是，2：不是
	/**
	 * 12个长度的订单号
	 * @param currTime
	 * @return
	 */
	public static String getOrderNo(Date currTime){//yyMMdd+6位随机数 再反转字符串
		StringBuilder sb = new StringBuilder(CommonConstants.DATE_SHORT_STR_FORMAT(currTime));
		for (int i = 0; i < 5; i++) {
			sb.append(numArr[random.nextInt(10)]);
		}
		sb.append(numArrNoZero[random.nextInt(9)]);
		sb.reverse();
		return sb.toString();
	}
	
	/**
	 * 生成合约编号
	 * @return
	 */
	public static String getContractNo(Date currTime){
		StringBuilder sb = new StringBuilder(CommonConstants.DATE_SHORT_STR_FORMAT(currTime));
		for (int i = 0; i < 5; i++) {
			sb.append(numArr[random.nextInt(10)]);
		}
		sb.append(numArrNoZero[random.nextInt(9)]);
		sb.reverse();
		String string = sb.toString();
		return "C"+string;
	}
	/**
	 * 14个长度的订单号 租客订单号
	 * @param currTime
	 * @return
	 */
	public static String getRenterOrderNoYYYY(Date currTime){//yyyyMMdd+6位随机数 再反转字符串
		StringBuilder sb = new StringBuilder(CommonConstants.DATE_STR_FORMAT(currTime));
		for (int i = 0; i < 5; i++) {
			sb.append(numArr[random.nextInt(10)]);
		}
		sb.append(numArrNoZero[random.nextInt(9)]);
		sb.reverse();
		return sb.toString();
	}
	
	public static String getRenterOrderNo(Date currTime){//yyMMdd+6位随机数 再反转字符串
		StringBuilder sb = new StringBuilder(CommonConstants.DATE_SHORT_STR_FORMAT(currTime));
		for (int i = 0; i < 5; i++) {
			sb.append(numArr[random.nextInt(10)]);
		}
		sb.append(numArrNoZero[random.nextInt(9)]);
		sb.reverse();
		return sb.toString()+"06";  //固定尾号为“06”
	}
	
	/**
	 * 充值订单号
	 * @param currTime
	 * @return
	 */
	public static String getRechargeOrderNo(Date currTime){//yyMMdd+6位随机数 再反转字符串
		StringBuilder sb = new StringBuilder(CommonConstants.DATE_SHORT_STR_FORMAT(currTime));
		for (int i = 0; i < 5; i++) {
			sb.append(numArr[random.nextInt(10)]);
		}
		sb.append(numArrNoZero[random.nextInt(9)]);
		sb.reverse();
		return sb.toString()+"16";  //固定尾号为“16”
	}
	
	/**
	 * 卖保险订单号
	 * @param currTime
	 * @return
	 */
	public static String getInsOrderNo(Date currTime){//yyMMdd+6位随机数 再反转字符串
		StringBuilder sb = new StringBuilder(CommonConstants.DATE_SHORT_STR_FORMAT(currTime));
		for (int i = 0; i < 5; i++) {
			sb.append(numArr[random.nextInt(10)]);
		}
		sb.append(numArrNoZero[random.nextInt(9)]);
		sb.reverse();
		return sb.toString()+"26";  //固定尾号为“16”
	}
	
	/**
	 * 9位的随机数字（用户/车辆注册号）
	 * @return
	 */
	public static String getRandomRegNo(){
		
		return getRandomNum(9);
	}
	
	/**
	 * 6位短信验证码
	 * @return
	 */
	public static String getSmsCode(){
		return getRandomNum(6);
	}
	/**
	 * 8个长度的随机字符串(包含：字母、数字)
	 * @return
	 */
	/*public static String getResetPwdVerifyCode(){
		
		return getRandom(charAndNumArr, 8);
	}*/
	
	/**
	 * 6个长度的随机密码
	 * @return
	 */
	/*public static String getNewRandomPwd(){
		
		return getRandom(numArr, 6);
	}*/
	/**
	 * 随机字符串
	 * @param length
	 * @return
	 */
	/*public static String getRandomString(int length) { 
		if(length <= 0){
			return "";
		}
	    StringBuffer sb = new StringBuffer(); 
	    int range = charArr.length; 
	    for (int i = 0; i < length; i ++) { 
	        sb.append(charArr[random.nextInt(range)]); 
	    } 
	    return sb.toString(); 
	}*/
	
	public static String getRandomNum(int length) { 
	    return getRandom(numArr, length); 
	}
	
	public static String getRandomNumUpChar(int length) { 
	    return getRandom(UpCharAndNumArr, length); 
	}
	/**
	 * 生成邀请码
	 * @param length
	 * @return
	 */
	public static String getRandomNumUpChar4INVITECODE(int length) { 
	    return getRandom(UpCharAndNumArr4INVITECODE, length); 
	}
	
	/**
	 * 返回包含字母（大、小写）、数字的 随机字符串
	 * @param length
	 * @return
	 */
	public static String getRandomCharAndNum(int length){
		return getRandom(charAndNumArr, length);
	}
	
	private static String getRandom(char[] charArray, int length){
		StringBuilder sb = new StringBuilder(); 
		int range = charArray.length; 
	    for (int i = 0; i < length; i++) {
			sb.append(charArray[random.nextInt(range)]);
		}
		return sb.toString();
	}
	
	//private static final SimpleDateFormat sdf_yyMMdd = new SimpleDateFormat(CommonConstants.DATE_SHORT_STR);
	/**
	 * 判断字符串格式的日期(yyMMdd)是否正确
	 * @param strDate
	 * @return
	 */
	public static boolean isDateStr(String strDate){
//		CommonConstants.DATE_SHORT_STR.setLenient(false);
		SimpleDateFormat DATE_SHORT_STR = new SimpleDateFormat("yyMMdd");
		DATE_SHORT_STR.setLenient(false);
		try {
			DATE_SHORT_STR.parse(strDate);
		} catch (ParseException e) {
			return false;
		}
		return true;
	}
	
	/**
	 * 生成长度为“fullLenght”的序列号，不足的位补“0”
	 * @param fullLenght 总长度
	 * @param seq 序列
	 * @return
	 */
	public static String fixedLengthSeq(int fullLenght,int seq){
		fullLenght = fullLenght + 1;
		String seqStr = String.valueOf(seq);
		for(int i = 0; i < (fullLenght - seqStr.length()); i++ ){
			seqStr = "0" + seqStr;
		}
		return seqStr;
	}
	/*public static void main(String[] args) {
		System.out.println(fixedLengthSeq(5,1));
	}*/
	
	/**
	 * 根据订单号判断是否是租客订单号
	 * @param orderNo
	 * @return
	 */
	public static boolean isRenterOrderNoYYYY(long orderNo){
		Date currDate = new Date();
		StringBuilder sb = new StringBuilder(CommonConstants.DATE_YEAR_FORMAT(currDate));  //当前年
		sb.reverse();
//		System.out.println(sb.toString());
		String str = sb.toString();
		if(String.valueOf(orderNo).endsWith(str)){
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * 170401 简化处理
	 * @param orderNo
	 * @return
	 */
	public static boolean isRenterOrderNo(long orderNo){
//		Date currDate = new Date();
//		StringBuilder sb = new StringBuilder(CommonConstants.DATE_YEAR_FORMAT(currDate));  //当前年
//		sb.reverse();
//		System.out.println(sb.toString());
//		String str = sb.toString();
		String str = "06";
		if(String.valueOf(orderNo).endsWith(str)){
			return true;
		}else{
			return false;
		}
	}
	
	public static boolean isRechargeOrderNo(long orderNo){
//		Date currDate = new Date();
//		StringBuilder sb = new StringBuilder(CommonConstants.DATE_YEAR_FORMAT(currDate));  //当前年
//		sb.reverse();
//		System.out.println(sb.toString());
//		String str = sb.toString();
		String str = "16";
		if(String.valueOf(orderNo).endsWith(str)){
			return true;
		}else{
			return false;
		}
	}
	
	public static boolean isInsOrderNo(long orderNo){
//		Date currDate = new Date();
//		StringBuilder sb = new StringBuilder(CommonConstants.DATE_YEAR_FORMAT(currDate));  //当前年
//		sb.reverse();
//		System.out.println(sb.toString());
//		String str = sb.toString();
		String str = "26";
		if(String.valueOf(orderNo).endsWith(str)){
			return true;
		}else{
			return false;
		}
	}
	
	public static void main(String[] args) {
		Date currDate = new Date();
		System.out.println(getOrderNo(currDate));
		System.out.println(getRenterOrderNo(currDate));
//		String s1 = "120299133071";
//		String s2 = "31495813307106";
		System.out.println("111="+isRenterOrderNo(120299133071l));
		System.out.println("222="+isRenterOrderNo(31495813307106l));
		
		//130865133071
		//31495813307102
		/*StringBuilder sb = new StringBuilder(CommonConstants.DATE_YEAR_FORMAT(currDate));  //当前年
		sb.reverse();
		System.out.println(sb.toString());
		String str = sb.toString();
		if(s1.endsWith(str)){
			System.out.println("111111111");
		}
		if(s2.endsWith(str)){
			System.out.println("222222222");
		}*/
		
	}
	/**
	 * 读取远程文件
	 * @param fileName
	 * @return
	 * @throws FileNotFoundException
	 */
	public static String imgRemoteToBase64(String fileName) throws FileNotFoundException{
		String base64Str = null;
		InputStream in = null;
		try {
			URL url = new URL(fileName);
			in = url.openStream();
			byte[] bytes = new byte[in.available()];
			in.read(bytes);
			//base64Str = new BASE64Encoder().encode(bytes);
			base64Str = Base64.encodeBase64String(bytes);
		}catch(FileNotFoundException e){
			throw e;
		}catch (Exception e) {
			e.printStackTrace();
		} finally{
			if(in != null){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return base64Str;
	}
	
	
	public static String imgToBase64(String fileName) throws FileNotFoundException{
		String base64Str = null;
		InputStream in = null;
		try {
			in = new FileInputStream(fileName);
			byte[] bytes = new byte[in.available()];
			in.read(bytes);
			//base64Str = new BASE64Encoder().encode(bytes);
			base64Str = Base64.encodeBase64String(bytes);
		}catch(FileNotFoundException e){
			throw e;
		}catch (Exception e) {
			e.printStackTrace();
		} finally{
			if(in != null){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return base64Str;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Map convertBean(Object bean) throws IntrospectionException, IllegalAccessException, InvocationTargetException {
		Class type = bean.getClass();
		Map returnMap = new HashMap();
		BeanInfo beanInfo = Introspector.getBeanInfo(type);
		PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
		for (int i = 0; i < propertyDescriptors.length; i++) {
			PropertyDescriptor descriptor = propertyDescriptors[i];
			String propertyName = descriptor.getName();
			if (!propertyName.equals("class")) {
				Method readMethod = descriptor.getReadMethod();
				Object result = readMethod.invoke(bean, new Object[0]);
				if (result != null) {
					returnMap.put(propertyName, result);
				} else {
					returnMap.put(propertyName, "");
				}
			}
		}
		return returnMap;
	}
	
	@SuppressWarnings("rawtypes")
	public static Object map2Bean(Class type, Map map) throws IntrospectionException, IllegalAccessException, InstantiationException,InvocationTargetException {
		Object obj = type.newInstance(); // 创建 JavaBean 对象
		BeanInfo beanInfo = Introspector.getBeanInfo(type); // 获取类信息
		PropertyDescriptor[] proDesc = beanInfo.getPropertyDescriptors();
		for (int i = 0; i < proDesc.length; i++) {
			PropertyDescriptor descriptor = proDesc[i];
			String propertyName = descriptor.getName();
			//descriptor.
			if (map.containsKey(propertyName)) {
				Object value = map.get(propertyName);
				descriptor.getWriteMethod().invoke(obj, value);
			}else{
				
			}
		}
		return obj;
	}
	
	@SuppressWarnings("rawtypes")
	public static Object mapToBean(Class type, Map map) throws IntrospectionException, IllegalAccessException, InstantiationException,InvocationTargetException {
		Object obj = type.newInstance(); // 创建 JavaBean 对象
		// 给 JavaBean 对象的属性赋值
		Field fieldlist[] = type.getDeclaredFields(); 
		for (Field field : fieldlist) {
			String propertyName = field.getName();
			//Annotation[] anns = field.getAnnotations();
			System.out.print("propertyName:"+propertyName);
			Class classType = field.getType();
			/*int ttt = 3;
			String t = (classType)ttt;*/
			if(classType.equals(String.class)){
				System.out.println("是字符串");
			}
			if(classType.equals(Integer.class)){
				System.out.println("是数字");
			}
			
			//得到这个属性的set方法
			if(map.containsKey(propertyName)){
				String value = String.valueOf(map.get(propertyName)) ;
				PropertyDescriptor pd = new PropertyDescriptor(propertyName, type); 
				Method setMethod = pd.getWriteMethod();  
				setMethod.invoke(obj, value);
			}
		}
		return obj;
	}

	public static final SimpleDateFormat sdf_MM = new SimpleDateFormat();
	
	/**
	 * 注册时生车辆图片的路径
	 * @param regNo
	 * @return
	 */
	public static String createCarBasePath(int carNo) {
		StringBuilder sb = getDatePath();
		sb.append(carNo);
		sb.append("/");
		return sb.toString();
	}
	
	/**
	 * 注册时生成用户存放文件的路径
	 * @param memNo
	 * @return
	 */
	public static String createUserBasePath(int memNo) {
		StringBuilder sb = getDatePath();
		sb.append(memNo);
		sb.append("/");
		return sb.toString();
	}
	
	/**
	 * 生成交易文件存的路径
	 * @param orderNo
	 * @return
	 */
	public static String createTransBasePath(String orderNo) {
		StringBuilder sb = getDatePath();
		sb.append(orderNo);
		sb.append("/");
		return sb.toString();
	}
	private static StringBuilder getDatePath(){
		Date date = new Date();
		String yearMonth = CommonConstants.DATE_SHORT_YEAR_MONTH_FORMAT(date);
		StringBuilder sb = new StringBuilder(yearMonth);
		sb.insert(2, "/");
		sb.append("/");
		return sb;
	}
	
	/**
	 * 
	 * @param picAbsPath 图片绝对路径
	 * @param picName 图片名
	 * @param picContent 图片Base64编码
	 * @param logger
	 * @return
	 */
	public static ErrorCode saveFile(String picAbsPath, String picName,String picContent,Logger logger){
		ErrorCode errorCode = ErrorCode.FAILED;
		boolean dirFlag = true;
		File file = new File(picAbsPath);
		if((dirFlag = file.exists()) == false){//判断路径是否存在
			dirFlag = file.mkdirs();
		}
		if(dirFlag == false){
			logger.error("创建图片目录失败");
		}else{
			//String filePath = picPath+ File.separator + jb.getId() + extName;
			String filePath = picAbsPath + picName;
			if(base64ToImg(picContent, filePath)){
				//存储的图片名为 ID + 图片原来扩展名
				logger.info("图片上传成功{}",filePath);
				errorCode = ErrorCode.SUCCESS;
			}else{
				logger.error("图片上传失败！{}",filePath);
			}
		}
		return errorCode;
	}
	
	public static boolean base64ToImg(String base64Str,String fileNameWithPath){
		ByteArrayInputStream in = null;
		FileOutputStream out = null;
		try {
			byte[] bytes = Base64.decodeBase64(base64Str);
			in = new ByteArrayInputStream(bytes);
			out = new FileOutputStream(fileNameWithPath);
			int byteRead = 0;
			byte[] buffer = new byte[1024];
			while((byteRead = in.read(buffer)) != -1){
				out.write(buffer,0,byteRead);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(out != null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(in != null){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		File file = new File(fileNameWithPath);
		return file.exists();
	}
	
	/**
	 * 过滤掉 emoji表情符
	 * @param source
	 * @return
	 */
	public static String filterEmoji(String str) {
		StringBuilder sb = new StringBuilder(str);
		for (int len = str.length(), i = len - 1; i >= 0; --i) {
			int codePoint = str.codePointAt(i);
			if (codePoint >= 127744) { // Emoji表情所在码位为U+1F300 – U+1F64F
				sb.deleteCharAt(i);
			}
		}
		return sb.toString();
	} 
	
	/**
	 * 判断是否还有emoji表情符号(未验证)
	 * @param source
	 * @return
	 */
	public static boolean containsEmoji(String str) {
		int len = str.length();
		for (int i = 0; i < len; i++) {
			char codePoint = str.charAt(i);
			if (isEmojiCharacter(codePoint)) {
				return true;
			}
		}
		return false;
	}

	private static boolean isEmojiCharacter(char codePoint) {

		return (codePoint == 0x0) ||
		(codePoint == 0x9) ||
		(codePoint == 0xA) ||
		(codePoint == 0xD) ||
		((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
		((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) ||
		((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
	}

	/**
	 * 转换成中文形式的日期
	 * @param dateTime yyyyMMddHHmmss
	 * @return  yyyy年mm月dd日
	 */
	public static String date2ChDate(long dateTime){
		String orderDateTmp = String.valueOf(dateTime);
		String fDate = "";
		if(orderDateTmp != null && orderDateTmp.length() >=8){
			fDate = orderDateTmp.substring(0, 4) + "年" + orderDateTmp.substring(4, 6) + "月" + orderDateTmp.substring(6, 8) + "日";
		}
		return fDate;
	}

	/**
	 * 得到车牌号的最后一个数字（如果尾号为字母，则再向左取，直到取到数字为止）
	 * @param carPlate
	 * @return
	 */
	public static String getCarPlateLastNum(String carPlate){
		String lastNum = "";
		if(StringUtils.hasText(carPlate)){
			StringBuilder sb = new StringBuilder(carPlate).reverse();
			for (int i = 0; i < sb.length(); i++) {
				char lastChar = sb.charAt(i);
				if(Character.isDigit(lastChar)){
					return String.valueOf(lastChar);
				}
			}
		}
		return lastNum;
	}
	
	public static String getLocalAddress(){
		try {
			Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
			InetAddress ip = null;
			while (allNetInterfaces.hasMoreElements()) {
				NetworkInterface netInterface = allNetInterfaces.nextElement();
				if("eth1".equals(netInterface.getName())){
					Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
					while (addresses.hasMoreElements()) {
						ip = (InetAddress) addresses.nextElement();
						if (ip != null && ip instanceof Inet4Address) {
							return ip.getHostAddress();
						}
					}
				}
			}
		} catch (Exception e) {
			logger.error("",e);
		}
		return "";
	}
	
	public static String getReqIpAddr(HttpServletRequest request) {
		String ip = null;
		try {
			ip = request.getHeader("x-forwarded-for");
			if (!StringUtils.hasText(ip) || "unknown".equalsIgnoreCase(ip)) {  
				ip = request.getHeader("Proxy-Client-IP");  
			}
			if (!StringUtils.hasText(ip) || "unknown".equalsIgnoreCase(ip)) {
			    ip = request.getHeader("WL-Proxy-Client-IP");
			}
			if (!StringUtils.hasText(ip) || "unknown".equalsIgnoreCase(ip)) {
			    ip = request.getRemoteAddr();
			}
		} catch (Exception e) {
			logger.error("",e);
		}
        return ip;  
    }
	
	/**
	 * 
	 * @author zg
	 * @version v1.0 (2015年5月26日 上午11:52:05)
	 * @param dateTimeStr
	 * @param sdf
	 * @return
	 */
	public static Date parseDateTime(String dateTimeStr, SimpleDateFormat sdf){
		if(!StringUtils.hasText(dateTimeStr)){
			return null;
		}
		Date date = null;
		try {
			date = sdf.parse(dateTimeStr);
		} catch (Exception e) {
			logger.warn("",e);
		}
		return date;
	}
	
	/**
	 * 
	 * @author zg
	 * @version v1.0 (2015年6月8日 下午6:09:46)
	 * @param dateStr "yyyy-MM-dd"
	 * @return
	 */
	public static LocalDate parseDate(String dateStr){
		if(!StringUtils.hasText(dateStr)){
			return null;
		}
		LocalDate date = null;
		try {
			date = LocalDate.parse(dateStr);
		} catch (Exception e) {
			logger.warn("",e);
		}
		return date;
	}
	
	//public static void main(String[] args) throws Exception{
		/*ObjectMapper mapper = new ObjectMapper();
		String str = "{\"\"verifyCode\" : 111111,"
				+ "\"mobile\" : \"13918842386\","
				+ "\"email\" : \"3709329999@qq.com\","
				+ "\"nickName\" : \"nelson\","
				+ "\"pwd\" : \"111111\"}";
		Map map = mapper.readValue(str, Map.class);*/
		//System.out.println(containsEmoji("abc"));
		
		//System.out.println(imgToBase64("C:\\Users\\lsl\\Desktop\\heiseche.jpg").length());
		
		//System.out.println(getOrderNo(new Date()));
		
//		System.out.println(getRandomNum(4));
		//System.out.println(imgToBase64("http://58.246.13.142:7070/HRM3_WEB_AOTU/photos/HRM3_AOTU.jpg"));
	//}
	

	public static boolean isMobile(String str) {   
	      Pattern p = null;  
	      Matcher m = null;  
	      boolean b = false;   
	      p = Pattern.compile("^[1][3,4,5,6,8][0-9]{9}$"); // 验证手机号  
	      m = p.matcher(str);  
	      b = m.matches();   
	      return b;  
	 }
	
	public static Integer toInteger(Object data){
		String result = toString(data);
		if(result !=null)
			return Integer.valueOf(result);
		throw new NullPointerException("参数为空");
	}
	
	public static String toString(Object data){
		if(data !=null && !"".equals(data)){
			return String.valueOf(data);
		}
		return null;
	}
	/**
	 * 检验银行卡是否合法
	 */
	 public static boolean isBankCard(String number){
	        int s1 = 0, s2 = 0;
	        String reverse = new StringBuffer(number.replace(" ", "")).reverse().toString();
	        for(int i = 0 ;i < reverse.length();i++){
	            int digit = Character.digit(reverse.charAt(i), 10);
	            if(i % 2 == 0){//this is for odd digits, they are 1-indexed in the algorithm
	                s1 += digit;
	            }else{//add 2 * digit for 0-4, add 2 * digit - 9 for 5-9
	                s2 += 2 * digit;
	                if(digit >= 5){
	                    s2 -= 9;
	                }
	            }
	        }
	        return (s1 + s2) % 10 == 0;
	    }
	 
	 
	
	/**
	 * 校验是否是数字
	 * @param str
	 * @return
	 */
	public static boolean isNumber(String str){
        java.util.regex.Pattern pattern=java.util.regex.Pattern.compile("^\\d*");
        java.util.regex.Matcher match=pattern.matcher(str);
        if(match.matches()==false) {
             return false;
        }else {
             return true;
        }
    }
}
 
